<template>
  <div class="course-detail" v-if="courseDetail">
    <section class="course-detail__hero">
      <div class="course-detail__hero-info">
        <p class="course-detail__badge">课程详情</p>
        <h1>{{ courseDetail.title }}</h1>
        <p class="course-detail__headline">{{ courseDetail.headline }}</p>
        <div class="course-detail__meta">
          <span>{{ difficultyLabels[courseDetail.difficulty] }}</span>
          <span>{{ courseDetail.lessonsCount }} 节内容</span>
          <span>{{ courseDetail.durationLabel }}</span>
        </div>
        <div class="course-detail__instructor">
          <span class="course-detail__instructor-name">{{ courseDetail.instructorName }}</span>
          <span class="course-detail__instructor-title">{{ courseDetail.instructorTitle }}</span>
        </div>
        <div class="course-detail__price">
          <span class="course-detail__price-current">{{ courseDetail.priceLabel }}</span>
          <span v-if="courseDetail.originalPrice" class="course-detail__price-original">{{ courseDetail.originalPrice }}</span>
        </div>
        <div class="course-detail__cta">
          <el-button
            type="primary"
            size="large"
            :loading="checkingAccess"
            @click="handlePrimaryAction"
          >
            {{ hasPurchased ? '开始学习' : '立即购买' }}
          </el-button>
          <!-- <el-button
            v-if="courseDetail.previewMedia"
            size="large"
            @click="handlePreview"
          >
            {{ courseDetail.previewMedia.type === 'video' ? '试看视频' : '试听音频' }}
          </el-button> -->
        </div>
      </div>
      <div class="course-detail__hero-media">
        <img :src="courseDetail.coverImage" :alt="courseDetail.title" loading="lazy" />
      </div>
    </section>

    <section class="course-detail__highlights">
      <h2>你将收获</h2>
      <ul>
        <li v-for="highlight in courseDetail.learningHighlights" :key="highlight">{{ highlight }}</li>
      </ul>
    </section>

    <section class="course-detail__layout">
      <main class="course-detail__content">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="课程介绍" name="intro">
            <article class="course-detail__section">
              <h3>课程概览</h3>
              <p>{{ courseDetail.description }}</p>
              <div class="course-detail__audience">
                <h4>适合人群</h4>
                <el-tag
                  v-for="audience in courseDetail.audience"
                  :key="audience"
                  size="large"
                  effect="dark"
                  round
                >
                  {{ audience }}
                </el-tag>
              </div>
            </article>
          </el-tab-pane>
          <el-tab-pane label="课程目录" name="outline">
            <article class="course-detail__section course-detail__outline">
              <el-collapse>
                <el-collapse-item
                  v-for="section in courseDetail.outline"
                  :key="section.id"
                  :name="section.id"
                >
                  <template #title>
                    <div class="course-detail__outline-title">
                      <strong>{{ section.title }}</strong>
                      <span>{{ section.summary }}</span>
                    </div>
                  </template>
                  <ul class="course-detail__lessons">
                    <li v-for="lesson in section.lessons" :key="lesson.id">
                      <span>{{ lesson.title }}</span>
                      <span class="course-detail__lesson-duration">{{ lesson.duration }}</span>
                    </li>
                  </ul>
                </el-collapse-item>
              </el-collapse>
            </article>
          </el-tab-pane>
          <el-tab-pane label="学员评价" name="reviews">
            <article class="course-detail__section course-detail__reviews">
              <el-empty v-if="!courseDetail.reviews.length" description="暂无评价，期待你的第一条反馈" />
              <el-card
                v-for="review in courseDetail.reviews"
                :key="review.id"
                shadow="never"
              >
                <div class="course-detail__review-header">
                  <span class="course-detail__reviewer">{{ review.reviewer }}</span>
                  <el-rate :model-value="review.rating" disabled show-score score-template="{value} 分" />
                </div>
                <h4>{{ review.highlight }}</h4>
                <p>{{ review.content }}</p>
                <span class="course-detail__review-date">{{ review.createdAt }}</span>
              </el-card>
            </article>
          </el-tab-pane>
        </el-tabs>
      </main>

      <aside class="course-detail__sidebar">
        <section class="course-detail__sidebar-block">
          <h3>推荐课程</h3>
          <ul>
            <li
              v-for="course in recommendedCourses"
              :key="course.id"
              role="button"
              tabindex="0"
              @click="openCourseDetail(course.id)"
              @keyup.enter="openCourseDetail(course.id)"
              @keyup.space.prevent="openCourseDetail(course.id)"
            >
              <div class="course-detail__sidebar-info">
                <strong>{{ course.title }}</strong>
                <span>{{ course.priceLabel }}</span>
              </div>
              <span class="course-detail__sidebar-link">查看详情</span>
            </li>
          </ul>
        </section>
        <section class="course-detail__sidebar-block">
          <h3>常见问题</h3>
          <ul class="course-detail__faq">
            <li>购买后可在「我的课程」无限次回看。</li>
            <li>支持 7 天无理由退款（试听课除外）。</li>
            <li>如需分期或团购，请联系课程助理。</li>
          </ul>
        </section>
      </aside>
    </section>
  </div>
  <el-empty
    v-else
    class="course-detail__empty"
    description="未找到对应课程，可返回课程中心继续浏览"
  >
    <el-button type="primary" @click="router.push({ name: 'course-center' })">回到课程中心</el-button>
  </el-empty>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

import { courseCatalogMock, courseDetailsMock } from './course.mock'
import { checkCourseAccess } from '../../api/course/access'
import { useAuthStore } from '../../stores/auth/auth'
import type { CourseDetail, CourseItem } from '../../types/course/Course.ts'

defineOptions({
  name: 'CourseDetailView',
})

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const difficultyLabels: Record<CourseDetail['difficulty'], string> = {
  BEGINNER: '入门',
  INTERMEDIATE: '进阶',
  ADVANCED: '高阶',
}

const activeTab = ref<'intro' | 'outline' | 'reviews'>('intro')

const checkingAccess = ref(false)
const hasPurchased = ref(false)

const isLoggedIn = computed(() => authStore.isLoggedIn)

const courseId = computed(() => route.params.courseId as string)

const courseDetail = computed<CourseDetail | undefined>(() => courseDetailsMock[courseId.value])

const recommendedCourses = computed<CourseItem[]>(() =>
  courseCatalogMock.filter((item) => item.id !== courseId.value).slice(0, 4),
)

const openCourseDetail = (id: string) => {
  const resolved = router.resolve({ name: 'course-detail', params: { courseId: id } })
  if (typeof window !== 'undefined') {
    window.open(resolved.href, '_blank', 'noopener')
  }
}

const refreshCourseAccess = async () => {
  if (!courseId.value) {
    hasPurchased.value = false
    return
  }

  if (!isLoggedIn.value) {
    hasPurchased.value = false
    return
  }

  checkingAccess.value = true
  try {
    const result = await checkCourseAccess(courseId.value)
    hasPurchased.value = result.purchased
  } catch (error) {
    console.warn('检查课程访问权限失败', error)
    hasPurchased.value = false
  } finally {
    checkingAccess.value = false
  }
}

const handlePurchase = async () => {
  if (!courseDetail.value) return
  if (!isLoggedIn.value) {
    try {
      await ElMessageBox.alert('请先登录后再购买课程。', '未登录提示', {
        confirmButtonText: '前往登录',
        type: 'warning',
      })
    } catch (error) {
      // ignore dismiss
    } finally {
      router.push({ name: 'login', query: { redirect: route.fullPath } })
    }
    return
  }

  ElMessage.info('购买通道即将开启，请联系课程助理获取最新方案。')//这里点击购买后的逻辑
}

const handleStartLearning = () => {
  if (!courseDetail.value) return
  router.push({ name: 'course-learn', params: { courseId: courseDetail.value.id } })
}

const handlePrimaryAction = () => {
  if (hasPurchased.value) {
    handleStartLearning()
  } else {
    handlePurchase()
  }
}

const handlePreview = () => {
  const media = courseDetail.value?.previewMedia
  if (!media) return
  if (typeof window !== 'undefined') {
    window.open(media.url, '_blank', 'noopener')
  }
}

watch(
  courseDetail,
  (detail) => {
    if (detail) {
      document.title = `${detail.title} - 课程详情`
    }
  },
  { immediate: true },
)

watch(
  [courseId, isLoggedIn],
  () => {
    refreshCourseAccess()
  },
  { immediate: true },
)
</script>

<style scoped>
.course-detail {
  display: flex;
  flex-direction: column;
  gap: 48px;
  padding: 48px 64px 96px;
  background-color: #f8f9fb;
}

.course-detail__hero {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 48px;
  align-items: center;
  padding: 48px;
  border-radius: 32px;
  background: linear-gradient(135deg, #eef2ff 0%, #fef9f5 100%);
  box-shadow: 0 24px 48px rgba(15, 23, 42, 0.08);
}

.course-detail__hero-info {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.course-detail__badge {
  align-self: flex-start;
  padding: 6px 14px;
  border-radius: 999px;
  background: rgba(60, 101, 245, 0.12);
  color: #3c65f5;
  font-weight: 600;
}

.course-detail__hero-info h1 {
  font-size: 40px;
  font-weight: 700;
  line-height: 1.2;
  color: #111827;
}

.course-detail__headline {
  font-size: 18px;
  color: #4b5563;
  line-height: 1.6;
}

.course-detail__meta,
.course-detail__instructor {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  color: #374151;
  font-weight: 600;
}

.course-detail__instructor-name {
  font-size: 16px;
}

.course-detail__instructor-title {
  font-size: 14px;
  color: #6b7280;
}

.course-detail__price {
  display: flex;
  align-items: baseline;
  gap: 12px;
}

.course-detail__price-current {
  font-size: 28px;
  font-weight: 700;
  color: #f97316;
}

.course-detail__price-original {
  font-size: 16px;
  color: #9ca3af;
  text-decoration: line-through;
}

.course-detail__cta {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.course-detail__hero-media img {
  width: 100%;
  border-radius: 28px;
  box-shadow: 0 18px 42px rgba(60, 101, 245, 0.18);
  object-fit: cover;
}

.course-detail__highlights {
  background: #fff;
  border-radius: 24px;
  padding: 32px 40px;
  box-shadow: 0 18px 36px rgba(15, 23, 42, 0.08);
}

.course-detail__highlights h2 {
  font-size: 26px;
  margin-bottom: 16px;
}

.course-detail__highlights ul {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 16px;
  list-style: none;
  padding: 0;
  margin: 0;
}

.course-detail__highlights li {
  position: relative;
  padding-left: 20px;
  color: #374151;
}

.course-detail__highlights li::before {
  content: '•';
  position: absolute;
  left: 0;
  color: #3c65f5;
  font-weight: 700;
}

.course-detail__layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 32px;
}

.course-detail__content {
  background: #fff;
  border-radius: 24px;
  padding: 32px;
  box-shadow: 0 20px 40px rgba(15, 23, 42, 0.08);
}

.course-detail__section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.course-detail__section h3 {
  font-size: 24px;
  font-weight: 700;
}

.course-detail__audience {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.course-detail__outline-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.course-detail__outline-title span {
  color: #6b7280;
  font-size: 14px;
}

.course-detail__lessons {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.course-detail__lessons li {
  display: flex;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 12px;
  background: rgba(59, 130, 246, 0.08);
  color: #1f2937;
}

.course-detail__lesson-duration {
  color: #3b82f6;
  font-weight: 600;
}

.course-detail__reviews el-card {
  margin-bottom: 16px;
}

.course-detail__review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.course-detail__reviewer {
  font-weight: 600;
  color: #1f2937;
}

.course-detail__review-date {
  color: #9ca3af;
  font-size: 14px;
}

.course-detail__sidebar {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.course-detail__sidebar-block {
  background: #fff;
  border-radius: 20px;
  padding: 24px;
  box-shadow: 0 18px 36px rgba(15, 23, 42, 0.08);
}

.course-detail__sidebar-block h3 {
  font-size: 20px;
  margin-bottom: 16px;
}

.course-detail__sidebar-block ul {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.course-detail__sidebar-block li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  padding: 12px 0;
  border-bottom: 1px solid rgba(15, 23, 42, 0.08);
}

.course-detail__sidebar-block li:last-child {
  border-bottom: none;
}

.course-detail__sidebar-block li:hover .course-detail__sidebar-link,
.course-detail__sidebar-block li:focus-visible .course-detail__sidebar-link {
  color: #3c65f5;
}

.course-detail__sidebar-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.course-detail__sidebar-link {
  color: #6b7280;
  font-size: 14px;
}

.course-detail__faq li {
  color: #4b5563;
  line-height: 1.6;
}

.course-detail__empty {
  padding: 96px 0;
}

@media (max-width: 1200px) {
  .course-detail__layout {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 960px) {
  .course-detail {
    padding: 36px 24px 72px;
    gap: 32px;
  }

  .course-detail__hero {
    padding: 36px;
  }
}

@media (max-width: 640px) {
  .course-detail {
    padding: 28px 16px 56px;
  }

  .course-detail__hero {
    padding: 28px;
  }

  .course-detail__hero-info h1 {
    font-size: 32px;
  }
}
</style>
